package com.pingxx.demo.integration;

import com.pingxx.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@Component
public class RedisLockSample {

    private RedisLockRegistry redisLockRegistry;

    public void process(String orderNo) {
        Lock lock = redisLockRegistry.obtain("orderNo:" + orderNo);
        boolean result = false;
        try {
            result = lock.tryLock(1000L, TimeUnit.MICROSECONDS);
            if (result) {
                //todo
                log.info("working....");
            }
        } catch (InterruptedException e) {
            //
            log.error("lock error", e);
        } finally {
            if (result) {
                lock.unlock();
            }
        }
    }

    /**
     * 使用第一个参数
     *
     * @param orderNo
     */
    @DistributedLock(expression = "#arg[0]")
    public void process1(String orderNo) {
        //todo
        log.info("working....");
    }

    /**
     * 使用第二个参数的name属性
     *
     * @param orderNo
     * @param user
     */
    @DistributedLock(expression = "#arg[1].name")
    public void process1(String orderNo, User user) {
        //todo
        log.info("working....");
    }

    /**
     * 使用第一个参数和第二个参数的name属性
     *
     * @param orderNo
     * @param user
     */
    @DistributedLock(expression = "#arg[0] + #arg[1].name")
    public void process2(String orderNo, User user) {
        //todo
        log.info("working....");
    }

    /**
     * 使用常量
     *
     * @param orderNo
     * @param user
     */
    @DistributedLock(expression = "'test3'")
    public void process3(String orderNo, User user) {
        //todo
        log.info("working....");
    }

    public RedisLockRegistry getRedisLockRegistry() {
        return redisLockRegistry;
    }

    @Autowired
    public void setRedisLockRegistry(RedisLockRegistry redisLockRegistry) {
        this.redisLockRegistry = redisLockRegistry;
    }
}
